import { ReqUser } from '@common/auth';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, ObjectId, Types } from 'mongoose';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User, UserDocument } from './schemas/user.schema';
import { UserFocus, UserFocusDocument } from './schemas/userFocus.schema';
import { FileUpload, UploadStrategy } from '@domain/uploadStrategy';
import { PhotosProfile, PhotosProfileDocument } from '@api/photos/schemas/photosProfile.schema';

@Injectable()
export class UserService {
    constructor(
        @InjectModel(User.name) private userModel: Model<UserDocument>,
        @InjectModel(UserFocus.name) private userFocusModel: Model<UserFocusDocument>,
        @InjectModel(PhotosProfile.name) private photosProfileModel: Model<PhotosProfileDocument>
    ) {}

    async create(createUserDto: CreateUserDto) {
        const createdCat = new this.userModel(createUserDto);
        const res = await createdCat.save();
        console.log(res);
        return res;
    }

    findAll() {
        return `This action returns all user`;
    }
    async getUserInfo(reqUser: ReqUser) {
        const [user, foucsCount, fansCount, userPhotosProfile] = await Promise.all([
            this.userModel.findById(reqUser._id, { password: 0, roles: 0 }).exec(),
            this.userFocusModel.find({ user: reqUser._id }).count(),
            this.userFocusModel.find({ beFocusUser: reqUser._id }).count(),
            this.photosProfileModel.aggregate([
                { $match: { user: new Types.ObjectId(reqUser._id) } },
                {
                    $group: {
                        _id: null,
                        sum: { $sum: '$totalDown' },
                    },
                },
            ]),
        ]);
        if (!user) throw new BadRequestException('未找到当前用户');
        const popularCount = userPhotosProfile[0]?.sum ?? 0;

        return { ...user.toObject(), foucsCount, fansCount, popularCount };
    }
    async findById(_id: string & ObjectId, reqUser: ReqUser) {
        // console.log(_id);
        const [user, foucsCount, fansCount, currentUserIsFocus, userPhotosProfile] = await Promise.all([
            this.userModel.findById(_id, { password: 0, roles: 0 }).exec(),
            this.userFocusModel.find({ user: _id }).count(),
            this.userFocusModel.find({ beFocusUser: _id }).count(),
            this.userFocusModel.findOne({ user: reqUser._id, beFocusUser: _id }),
            this.photosProfileModel.aggregate([
                { $match: { user: new Types.ObjectId(_id) } },
                {
                    $group: {
                        _id: null,
                        sum: { $sum: '$totalDown' },
                    },
                },
            ]),
        ]);
        if (!user) throw new BadRequestException('未找到当前用户');
        // console.log({ userPhotosProfile });
        const popularCount = userPhotosProfile[0]?.sum ?? 0;
        return {
            ...user.toObject(),
            foucsCount,
            fansCount,
            popularCount,
            currentUserIsFocus: Boolean(currentUserIsFocus),
        };
    }

    async findOneByUsername(username: string): Promise<UserDocument> {
        const res = await this.userModel.findOne({ username }).exec();
        return res;
    }

    async update(_id: string, updateUserDto: UpdateUserDto) {
        return await this.userModel.findByIdAndUpdate(_id, updateUserDto).exec();
    }
    async uploadAvatar(reqUser: ReqUser, files: Express.Multer.File[]) {
        const fileUpload = new FileUpload(UploadStrategy.USER_AVATAR_UPLOAD);
        const fileUrl = await fileUpload.upload(reqUser, files);
        return await this.update(reqUser._id, { avatar: fileUrl[0] });
    }
    remove(id: number) {
        return `This action removes a #${id} user`;
    }
}
